package swu.myt.records;

import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import swu.myt.DBUtils;
import swu.myt.Say;

public class SayingServlet extends HttpServlet{

	private static final long serialVersionUID = -2611737898641260268L;
	
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        this.doPost(request, response);
     }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String page = request.getParameter("page");

        int offset = (Integer.valueOf(page).intValue() - 1) * 9;//设置偏移量
        
        HttpSession session=request.getSession();
		
		String username = (String)session.getAttribute("username");

        String sql = "SELECT * FROM "+username+"says ORDER by submission_date desc LIMIT 9 OFFSET " + offset+";";

        System.out.println(sql);//测试检查sql语句

        try {
            List<Say> says = DBUtils.limGetsayings(sql);//用DBUtils得到限制数量的日记
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            try(Writer writer = response.getWriter()) {
                writer.write(this.toJson(says));//得到json数据类型
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        }
        
    
      //用得到的日记数据写json类
      private String toJson(List<Say> says) {
          StringBuilder sb = new StringBuilder();
          sb.append("{");
          sb.append("\"says\": [");

          for(int i=0; i<says.size(); i++) {
              Say say = says.get(i);
              if (i > 0) sb.append(",");
              sb.append(String.format(
                  "{\"date\": \"%s\", \"saying\": \"%s\",\"pic\": \"%s\"}",
                  say.getDate(),say.getSay(),say.getPic() ));
             }

          sb.append("]");
          sb.append("}");
          System.out.println(sb.toString());
          return sb.toString();
      }
       
    
}
